$(document).ready(function(){
    // Active item in the list
    $("#main").on("click", ".selectList li a", function(event){
        event.preventDefault();
        
        $(this).parents(".selectList").find("li a").not(this).removeClass("active");
        
        if ($(this).hasClass("active")){
            $(this).removeClass("active");
        }else{
            $(this).addClass("active");
        }        
    });
    
    // Process
    // 1. Select Question (master) 
    // 2. Select File and call service to get the question list
    // 3. Select Question
    
    // -- 1 --
    $("#main").on("click", ".selectQuestionMaster li a",function(){
        // Reset lists
        $(".selectFile").attr("data-parent", "").html("");
        $(".selectQuestion").attr("data-parent", "").html("");
        
        if (!$(this).hasClass("active"))
            return false;
        
        var id = $(this).data("id");
        
        $("#master_questions").find("ul.all[data-id="+id+"]").children("li").each(function(){
            var name = $(this).text();
            var klass = $(this).attr("class");
            var file_id = $(this).data("value");
            var blocked = "";
            if (klass == "bullet_ok"){
                blocked = "data-blocked='1'";
            }
            var option = $("<li><a data-id='"+file_id+"' class='"+klass+" reference_sav_file selectable_item' "+blocked+">"+name+"</a></li>");
            $(".selectFile").append(option);
        });
        
        // Set Parent ID
        $(".selectFile").attr("data-parent", id);

    });
     
    // -- 2 --
    $("#main").on("click", ".selectFile li a", function(){
        // Reset lists
        $(".selectQuestion").attr("data-parent", "").html("");

        if (!$(this).hasClass("active"))
            return false;
        
        // Validation
        if ($(this).data("blocked") == 1)
            return false;

        var params = {
            savid: $(this).attr("data-id")
        };
        $.ajax({
            url: "/questions/getQuestionsBySavId.do",
            data: params
        })
        .done(function(data) {
            for(var index in data){
                var option = $("<li class='selectable_item'><a href='#'>"+data[index]+"</a></li>");
                $(".selectQuestion").append(option);
            }
            
            // Set Parent ID
            $(".selectQuestion").attr("data-parent", params.savid);
        });            
     });
     
     // -- 3 --
    $("#main").on("click", ".selectQuestion li a", function(){
        checkers.selectedQuestion();
        updateMatching();
    });
   
    // Normalization Actions
    $(".btn_normalization_actions").on("click",function(event){
        event.preventDefault();

        var actiontype = $(this).data("action");
        if(actiontype=="ok"){
            // Validation & Process
            var error = validateData();
            if (error == 1){
                $("#myModal").find(".modal-body").html("All questions should be normalized");
                $('#myModal').modal({'show': true});
                return false;
            }else{
                // Normalize data
                var params = {
                   transactionId: $("#transactionId").val()
                }
                $.ajax({
                    url: "/questions/confirmMatching.do",
                    data: params
                }).done(function(data,result){
                    // OK
                }).fail(function(){
                    // ERROR
                    alert("Normalization Save Error");
                });
            }
        } else {
            // Button Cancel Actions
        }
    });
     
     
    // Search Questions
    $("#btn_search_question").on("click", function(event){
        // Get the search value and trim
        var textToSearch = jQuery("#search_question").val();
        textToSearch = textToSearch.replace(/^\s+/g,'').replace(/\s+$/g,'');
        jQuery("#search_question").val(textToSearch);
        
        // Lowercase string searched
        textToSearch = textToSearch.toLowerCase();
        
        // Search in reports list
        jQuery(".selectQuestion").children("li").each(function(){
            var question = $(this).children("a");
            
            if (textToSearch.length > 0){
                if(question.text().toLowerCase().indexOf(textToSearch) == -1){
                    question.parent("li").hide();
                }else{
                    question.parent("li").show();
                }
            }else{
                question.parent("li").show();
            }
        });
        
        // Add reset search button
        $(".reset_search").remove();
        if (textToSearch != ""){
            $("#search_question").addClass("searched");
            $("#search_question").after('<i class="icon-remove reset_search"></i>');
        }else{
            $("#search_question").removeClass("searched");
            $(".reset_search").remove(); 
        }
    });
    
    // Listen "Enter" keypressed in search box
    $("#search_question").on("keypress", function(e){
        if (e.which == 13) {
            $("#btn_search_question").click();
        }
    });
    
    // Listen Reset search button
    $("#main").on("click", ".reset_search", function(){
        $("#search_question").val("").removeClass("searched");
        $(this).remove(); 
        $("#btn_search_question").click();               
    });
    
 // Drop selected master question
    $("#btn_drop_master_question").on("click",function(){
    	var data = {
    			   questionToDrop: $(".selectQuestionMaster").children("li").children("a.active").text(),
    		       transactionId: $("#transactionId").val()
    		   };
    	$.ajax({
            url: "/questions/dropmasterquestion.do",
            type: "GET",
            data: data                	
        }).done(function(questionData){
        	if(questionData.length>0) {
        		
            	reFillMasterQuestionList(questionData);
            	
        	}        	
        });        
    });
    
});




// ----- FUNCTIONS -----

function validateData(){
   var error = 0;
   
   $("#master_questions").children("li").each(function(){
       var isOk = $(this).children("a").hasClass("bullet_ok");
       
       if (isOk ==  false){
           error = 1;
       }
   });
   
   return error;
}

function updateMatching(){
   var data = {
       masterQuestion: $(".selectQuestionMaster").children("li").children("a.active").text(),
       sameQuestions: $(".selectQuestion").children("li").children("a.active").text(),
       sav_id: $(".selectFile").children("li").children("a.active").data("id"),
       transactionId: $("#transactionId").val()
   }
   
   $.ajax({
        url: "/questions/updateMatching.do",
        data: data,
        dataType: "json",
        type: "GET"
    }).done(function(data,result){
        // OK
        //console.log("Saved");
    }).fail(function(){
        // ERROR
        alert("Conection error");
    });
}

// Checkers
checkers = {
   selectedQuestion : function(){
       var parentId = $(".selectQuestion").attr("data-parent");       
       var qtySelected = $(".selectQuestion").children("li").children("a.active");
       
       // Update Files
       if(qtySelected.length == 1){
           checkers.selectedFile(parentId, true);
       }else{
           checkers.selectedFile(parentId, false);
       }
   },
   
   selectedFile : function(id, action){
       var file = $(".selectFile").children("li").children("a[data-id='"+id+"']");
       var parentId = file.parents("ul").attr("data-parent");
       
       if (action == true){
           file.addClass("bullet_ok");
           file.removeClass("bullet_error");
       }else{
           file.addClass("bullet_error");
           file.removeClass("bullet_ok");
       }
       
       // Update Questions Master
       var normalized;
       var counter = {
           "ok": 0,
           "error": 0
       };
       
       $(".selectFile").children("li").each(function(){
           if ($(this).children("a").hasClass("bullet_ok")){
               counter.ok += 1;
           }
           else if($(this).children("a").hasClass("bullet_error")){
               counter.error += 1;
           }
       });
       
       if (counter.ok > 0 && counter.error == 0){
           normalized = "ok";
       }
       else if (counter.ok > 0 && counter.error > 0){
           normalized = "warning";
       }
       else if (counter.ok == 0 && counter.error > 0){
           normalized = "error";
       }
       
       checkers.selectedQuestionMaster(parentId, normalized);
   },
   
   selectedQuestionMaster : function(id, action){
       var question = $(".selectQuestionMaster").children("li").children("a[data-id='"+id+"']");
       
       if (action == "ok"){
           question.addClass("bullet_ok");
           question.removeClass("bullet_warning");
           question.removeClass("bullet_error");
       }
       else if(action == "warning"){
           question.addClass("bullet_warning");
           question.removeClass("bullet_ok");
           question.removeClass("bullet_error");
       }
       else if(action == "error"){
           question.addClass("bullet_error");
           question.removeClass("bullet_ok");
           question.removeClass("bullet_warning");
       }
   }
}

function reFillMasterQuestionList(data){
	var questions = data;
	//Clean lists
	$(".selectQuestionMaster").html('');
	$(".selectFile").html('');
	$(".selectQuestion").html('');
	//Refill master question list
	for(var i=0; i<questions.length; i++) {
		// Check Status
		var bullet = "";
		var blocked = 0;
		if (questions[i].result == "ALL"){
			bullet = "bullet_ok";
			blocked = 1;
		}
		if (questions[i].result == "SOME") bullet = "bullet_warning";
		if (questions[i].result == "NONE") bullet = "bullet_error";
		
		// Create elements
		var liQuestion = $("<li></li>");
		var liQuestionA = $("<a></a>");
		liQuestionA
			.addClass(bullet + " question_item selectable_item")
			.attr("data-id", i)
			.html(questions[i].question);
		
		if (blocked == 1){
			liQuestionA.attr("data-blocked", "1");
		}
		
		liQuestionA.appendTo(liQuestion);
		liQuestion.appendTo($(".selectQuestionMaster"));
		
		// Create sublist
		var filesList = $('<ul class="all hide" data-id="' + i + '"></ul>');
		var files = questions[i].savItems;
		var bulletFile;
		
		for (var f=0; f<files.length; f++){
			if (files[f].present == true){
				bulletFile = "bullet_ok";
			}else{
				bulletFile = "bullet_error";
			}
			
			var liFile = $("<li></li>");
			liFile
				.addClass(bulletFile)
				.attr("data-value", files[f].id)
				.attr("data-selected", "0")
				.html(files[f].name);
			
			liFile.appendTo(filesList);
			filesList.appendTo($(".selectQuestionMaster"));
		}
		
		
	}
}